﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;
using XuanFe.AppLaunch.Common;
using XuanFe.Database.BLL;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.AppLaunch
{
    public partial class AppendCustomerForm : DevExpress.XtraEditors.XtraForm
    {
        private const string m_ModuleId = "0201";

        private string m_CustomerId;
        private bool m_AllowFollowStaffId;
        public AppendCustomerForm(string customerId, bool allowFollowStaffId)
        {
            InitializeComponent();

            this.m_CustomerId = customerId;
            this.m_AllowFollowStaffId = allowFollowStaffId;
        }
        private bool ValidityCheck()
        {
            this.errorProvider1.ClearErrors();
            string message = string.Empty;
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerName, message);
                this.txtCustomerName.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerMobileNumber, false, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerMobileNumber, message);
                this.txtCustomerMobileNumber.Focus();
                return (false);
            }
            if (!string.IsNullOrWhiteSpace(this.txtCustomerMobileNumber.Text) && !Global.Instance.IsPhoneNumber(this.txtCustomerMobileNumber.Text))
            {
                this.errorProvider1.SetError(this.txtCustomerMobileNumber, "该字段格式不符");
                this.txtCustomerMobileNumber.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.cmbCustomerSex, true, ref message))
            {
                this.errorProvider1.SetError(this.cmbCustomerSex, message);
                this.cmbCustomerSex.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerTelephone, true, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerTelephone, message);
                this.txtCustomerTelephone.Focus();
                return (false);
            }
            if (!string.IsNullOrWhiteSpace(this.txtCustomerTelephone.Text) && !Global.Instance.IsPhoneNumber(this.txtCustomerTelephone.Text))
            {
                this.errorProvider1.SetError(this.txtCustomerTelephone, "该字段格式不符");
                this.txtCustomerTelephone.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerEMail, true, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerEMail, message);
                this.txtCustomerEMail.Focus();
                return (false);
            }
            if (!string.IsNullOrWhiteSpace(this.txtCustomerEMail.Text) && !Global.Instance.IsEMail(this.txtCustomerEMail.Text))
            {
                this.errorProvider1.SetError(this.txtCustomerEMail, "该字段格式不符");
                this.txtCustomerEMail.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerContactAddress, true, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerContactAddress, message);
                this.txtCustomerContactAddress.Focus();
                return (false);
            }
            if (this.m_AllowFollowStaffId)
            {
                if (Global.Instance.MandatoryFieldEmpty(this.cmbFollowStaffId, false, ref message))
                {
                    this.errorProvider1.SetError(this.cmbFollowStaffId, message);
                    this.cmbFollowStaffId.Focus();
                    return (false);
                }
            }

            return (true);
        }
        /// <summary>
        /// 添加记录
        /// </summary>
        /// <returns></returns>
        private bool AppendRecord()
        {
            try
            {
                CustomerModel model = new CustomerModel()
                {
                    Id = this.m_CustomerId,
                    Name = this.txtCustomerName.Text.Trim(),
                    Sex = this.cmbCustomerSex.SelectedIndex,
                    Birthday = this.dtCustomerBirthday.DateTime,
                    MobileNumber = this.txtCustomerMobileNumber.Text.Trim(),
                    Telephone = this.txtCustomerTelephone.Text.Trim(),
                    EMail = this.txtCustomerEMail.Text.Trim(),
                    ContactAddress = this.txtCustomerContactAddress.Text.Trim(),
                    RegisterTime = DateTime.Now,
                    FollowStaffId = this.m_AllowFollowStaffId ? (this.cmbFollowStaffId.SelectedItem as StaffModel).Id : LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            CustomerDAL.Instance.Insert(tran, model);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        private void btnSaveCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ValidityCheck()) return;

                Global.Instance.BeginWait();

                string id = this.m_CustomerId;
                string name = this.txtCustomerName.Text.Trim();
                string mobileNumber = this.txtCustomerMobileNumber.Text.Trim();

                if (CustomerDAL.Instance.MobileNumberExist(mobileNumber))
                {
                    this.errorProvider1.SetError(this.txtCustomerMobileNumber, "该记录已存在！");
                    this.txtCustomerMobileNumber.Focus();
                    Global.Instance.WarningDlg(string.Format("电话“{0}”已经存在了", mobileNumber));
                    return;
                }

                if (!this.AppendRecord())
                {
                    Global.Instance.ErrorDlg("保存失败！");
                    return;
                }
                StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("新增编码为“{0} - {1} - {2}”的记录", id, name, mobileNumber));

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnCancelCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void AppendCustomerForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.m_AllowFollowStaffId)
                {
                    List<StaffModel> staffs = StaffDAL.Instance.Gets(true);
                    this.cmbFollowStaffId.Properties.Items.Clear();
                    this.cmbFollowStaffId.Properties.Items.AddRange(staffs);
                    this.cmbFollowStaffId.SelectedItem = staffs.Find(delegate (StaffModel item) { return string.Equals(item.Id, LoginInfo.Instance.StaffLogon.Staff.Id); });
                }
                else
                {
                    this.lcFollowStaffId.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }
    }
}